#include <bits/stdc++.h>
using namespace std;
#define ll long long
void swap(char &a, char &b)
{
    char temp = a;
    a = b;
    b = temp;
}
void solve()
{
    int t = 0;
    cin >> t;
    int i = 0;
    for (i = 0; i < t; i++)
    {
        int n = 0;
        cin >> n;
        string s;
        cin >> s;
        int j = 0;
        int Time = 0;
        /**/
        int last = -1;
        for (j = 0; j < n - 1; j++)
        {
            int flag = 0;
            if (s[j] == 'A' && s[j + 1] == 'B')
            {
                swap(s[j], s[j + 1]);
                Time++;
                int pre = j;
                int after = j;
                while (pre != 0)
                {
                    pre--;
                    if (s[pre] == 'A' && last != pre)
                    {
                        swap(s[pre], s[pre + 1]);
                        Time++;
                        flag = 1;
                    }
                    else
                        break;
                }
                while (after != n - 2)
                {
                    after++;
                    if (s[after + 1] == 'B')
                    {
                        swap(s[after], s[after + 1]);
                        Time++;
                        flag = 2;
                    }
                    else
                        break;
                }
                last = j;
                j = after - 1;
            }
        }
        cout << Time << endl;
    }
}
int main()
{
    solve();
    return 0;
}
